實現SearchBar的使用:
UISearchController的實現
可以先看下面的成果是不是想要的效果
import Firebase
import UIKit
class searchTableViewController:UITableView,UISearchResultsUpdating{
// 宣告一個UISearchController
var searchController:UISearchController!
// 宣告一個ref,因為要提取Firebase資料庫內的資料
var ref:DatabaseReference!
// 宣告儲存等等搜尋的資料的Array
var Data:[Book] = []
var Filter:[Book] = []
override func viewDidLoad(){
	super.viewDidLoad()
	ConfigSearchController()
	ConfigDatabase()
  
}
func ConfigDatabase(){
	// 建立一個Firebase的reference
	ref = Database.database().reference(withPath:"Book")
	// (.queryOrdered)透過child搜尋到資料,(.observe)提取資料中的value
	// Firebase提供的資料都會是snapshot
	ref.queryOrdered(byChild:"booktitle").observe(.value,with:{(snapshot) in
		let OnlineDataItem = [Book]()
		// snapshot下面的所有child
		for Items in snapshot.child{
				// 初始化進入Book類型內
				let book = Book(snapshot:Items as! DataSnapshot)
				OnlineDataItem.append(book)
	}
	// 初始化自己的Data資料,成為網路上獲取下來的資料
	self.Data = OnlineDataItem
}
func ConfigSearchController(){
	// 實例化UISearchController (讓搜尋結果顯示在與搜尋相同的視圖)
	searchController = UISearchController(searchResultsController:nil)
	// 讓SearchBar出現在tableView中
	tableView.tableHeaderView = searchController.searchBar
	// 指派執行searchController更新
	searchController.searchResultsUpdater = self
	// 設定search bar的placeholder
	searchController.searchBar.placeholder = "Search What you want"
}
}
有了這些資料,現在需要一個過濾的func來替我們過濾出資料
Filter負責儲存過濾後的資料
// 負責執行搜尋的func
func filterContent(for searchText:String){
	// 使用filter函數會將符合的項目儲存至Filter的Array內
	Filter = Data.filter({(data) -> Bool in
		let title = data.booktitle
		// matched 為Boolean值
		let matched = title.localizedCaseInsensitiveContains(searchText)
		if matched{
			return matched
		}else{
			return false
		}
}
繼承UISearchResultsUpdating的委派,會自動產生的upadateSearchResults(for searchController:)
傳入SearchController內的searchBar文字,讓視圖可以執行過濾的func
有了更新後的資料,就要負責更新視圖
// 負責更新結果的func
func updateSearchResults(for searchController:UISearchController){
	
	if let searchText = searchController.searchBar.text{
			// 執行搜尋
			filterContent(searchText)
			// 搜尋過後重新載入
			tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
	// 先去生一個tableViewCell,設定好要呈現的Cell,將其identifier改成searchIdentifier
	let cell = tableView.dequeueReusableCell(withIdentifier: "searchIdentifier", for: indexPath) as! SearchTableViewCell
        
  // 用來辨識要用哪個資料來呈現在TableView上      
	let end = (searchController.isActive) ? Filter[indexPath.row] : Data[indexPath.row]
        
  // 如果有啟用searchController,顯示Data的booktitle
	if searchController.isActive{
		cell.searchbooktitle.text = end.booktitle
		cell.searchauthors.text = end.bookauthors
		cell.searchbookisbn.text = end.bookISBN
	}
	else{   
		// 反之沒有啟用,則顯示所有的Data資料     
		cell.searchbooktitle.text = end.booktitle
		cell.searchauthors.text = end.bookauthors
		cell.searchbookisbn.text = end.bookISBN
	}
	return cell
}
成果展示:

參考網址:
如何利用UISearchController添加搜尋功能並打造客製化搜尋列